# -*- coding: utf-8 -*-

"""
@Datetime: 2019/2/10
@Author: Zhang Yafei
"""
import json
import traceback

from sqlalchemy import or_

from Kingadmin.admin import site
from flask import Blueprint, request, url_for, jsonify

from common.libs.UserService import UserService
from common.libs.helper import ops_render, getCurrentDate
from common.utils.pagination import Pagination
from common.models import models
from application import db


route_kingadmin = Blueprint('kingadmin_page', __name__)


@route_kingadmin.route('/table_list')
def table_list():
    print(site.enable_admins['user'].model.__verbose_name__)
    return ops_render('kingadmin/table_index.html', {'site':site})


@route_kingadmin.route('/table_list/<model_name>', endpoint='table_model', methods=['GET','POST'])
def table_obj_list(model_name):
    admin_class = site.enable_admins[model_name]
    model = admin_class.model
    query = model.query
    if request.method == 'GET':
        req = request.values
        page = int(req['p']) if ('p' in req and req['p']) else 1
        filer_fields = admin_class.list_filter
        print(filer_fields)
        if filer_fields and 'mix_kw' in req:
            conditions = []
            for field in filer_fields:
                conditions.append(getattr(model, field).ilike('%{}%'.format(req['mix_kw'])))
            condition = or_(*conditions)
            query = query.filter(condition)
        page_obj = Pagination(query.count(), request.args.get('p'), admin_class.list_per_page)
        base_url = url_for('kingadmin_page.table_model', model_name=model_name)
        page_str = page_obj.page_str(base_url=base_url)
        datasets = query.order_by(model.created_time.desc()).all()[page_obj.start:page_obj.end]
        context = {'datasets': datasets,'admin_class': admin_class,
                   'model_name': model_name, 'page_obj':page_obj,
                   'page_str':page_str,'search_con': req,
                   }
        return ops_render('kingadmin/table_obj_list.html',context)
    elif request.method == 'POST':
        resp = {'code': 1000}
        try:
            print(request.form)
            selected_ids = request.form.get('selected_ids')
            selected_ids = map(int, json.loads(selected_ids))
            db.session.query(model).filter(model.id.in_(selected_ids)).delete(synchronize_session=False)
            db.session.commit()  # or session.expire_all()
            resp['msg'] = '删除成功'
        except Exception as e:
            traceback.print_exc()
            resp['code'] = 1001
            resp['msg'] = '删除失败'
        return jsonify(resp)


@route_kingadmin.route('/table_list/<model_name>/add', endpoint='table_model_add', methods=['GET','POST'])
def table_obj_add(model_name):
    context = {}
    model = site.enable_admins[model_name].model
    if request.method == 'GET':
        cursor = db.session.execute("SELECT GROUP_CONCAT(COLUMN_NAME SEPARATOR ',') FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'flask_test' AND TABLE_NAME = (:table_name)", params={'table_name':model_name})
        results = cursor.fetchall()[0]
        context['model_name'] = model_name
        fields = results[0].split(',')
        if 'id' in fields:
            fields.remove('id')
        if 'created_time' in fields:
            fields.remove('created_time')
        if model == models.User:
            fields.remove('updated_time')
            fields.remove('login_salt')
        context['fields'] = fields
        return ops_render('kingadmin/table_obj_add.html', context)
    resp = {'code': 1000}
    form_data = request.form
    try:
        model_table = model()
        for k, v in form_data.items():
            setattr(model_table, k, v)
        if model == models.User:
            model_table.login_salt = UserService.geneSalt()
            model_table.login_pwd = UserService.genePwd(model_table.login_pwd, model_table.login_salt)
        model_table.created_time = getCurrentDate()
        db.session.add(model_table)
        db.session.commit()
        resp['msg'] = '添加成功'
    except Exception as e:
        traceback.print_exc()
        resp['code'] = 1001
        resp['msg'] = '添加失败'
    return jsonify(resp)


@route_kingadmin.route('/table_list/<model_name>/<int:id>', endpoint='table_model_detail')
def table_obj_detail(model_name, id):
    context = {}
    model = site.enable_admins[model_name].model
    data = model.query.filter_by(id=id).first()
    if request.method == 'GET':
        context['model_name'] = model_name
        context['data'] = data
        context['id'] = id
        data_dict = data.__dict__
        del data_dict['_sa_instance_state']
        del data_dict['id']
        del data_dict['created_time']
        fields = data_dict.keys()
        context['fields'] = fields
        return ops_render('kingadmin/table_obj_detail.html', context)


@route_kingadmin.route('/table_list/<model_name>/<int:id>/edit', endpoint='table_model_edit', methods=['GET','POST'])
def table_obj_edit(model_name, id):
    context = {}
    model = site.enable_admins[model_name].model
    data = model.query.filter_by(id=id).first()
    if request.method == 'GET':
        context['model_name'] = model_name
        context['data'] = data
        context['id'] = id
        data_dict = data.__dict__
        del data_dict['_sa_instance_state']
        del data_dict['id']
        del data_dict['created_time']
        fields = data_dict.keys()
        context['fields'] = fields
        return ops_render('kingadmin/table_obj_edit.html', context)
    form_data = request.form
    print(form_data)
    resp = {'code': 1000}
    try:
        db.session.query(model).filter_by(id=id).update(form_data)
        db.session.commit()
        resp['msg'] = '保存成功'
    except Exception as e:
        traceback.print_exc()
        resp['code'] = 1001
        resp['msg'] = '保存失败'
    return jsonify(resp)


@route_kingadmin.route('/table_list/<model_name>/<int:id>/delete', endpoint='table_model_delete', methods=['GET','POST'])
def table_obj_delete(model_name, id):
    if request.method == 'POST':
        print(model_name, id)
        resp = {'code':1000}
        model = site.enable_admins[model_name].model
        try:
            model.query.filter_by(id=id).delete()
            resp['msg'] = '删除成功'
            return jsonify(resp)
        except Exception as e:
            resp['code'] = 1001
            resp['msg'] = str(e)
            return jsonify(resp)
